/**
* @file server.cpp
* @describe server
* @author gaoyuelong
* @date 2022/1/3 
*/

#include "server.h"
#include "json.hpp"
#include "service.h"
#include <iostream>
#include <functional>
#include <muduo/base/Logging.h>
using namespace std;
using namespace placeholders;
using json = nlohmann::json;

Server::Server(EventLoop *loop, const InetAddress &listenAddr, const string &nameArg)
    : m_server(loop, listenAddr, nameArg), m_pLoop(loop) 
{
    m_server.setConnectionCallback(std::bind(&Server::onConnection, this, _1));

    m_server.setMessageCallback(std::bind(&Server::onMessage, this, _1, _2, _3));

    m_server.setThreadNum(2);
}

void Server::start()
{
    m_server.start();
}

void Server::onConnection(const TcpConnectionPtr &conn)
{
    if (!conn->connected()) {
        //客户端异常退出
        Service::instance()->clientCloseException(conn);
        conn->shutdown();
    }
}

void Server::onMessage(const TcpConnectionPtr &conn, Buffer *buffer, Timestamp time)
{
    string buf = buffer->retrieveAllAsString();
    json js = json::parse(buf);
    LOG_INFO << js["MessageType"].get<int>();
    //对消息筛选，如果不存在QoQoQo认为是非法消息
    auto msgHandler = Service::instance()->getHandler(js["MessageType"].get<int>());
    msgHandler(conn, js, time);
    return;
}